package com.bear.udisk.handler;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.bear.udisk.exception.CustomException;
import com.bear.udisk.model.Fileinfo;
import com.bear.udisk.model.Userinfo;
import com.bear.udisk.service.FileinfoService;
import com.bear.udisk.util.MyMD5Util;

@Controller
@RequestMapping("/fileinfo")
public class FileinfoHandler {

	@Autowired
	private FileinfoService fileinfoService;

	/**
	 * 加载文件列表
	 * 
	 * @return
	 */
	@RequestMapping("/list")
	public String list(HttpSession session, Model model) {
		// 从session中获取当前登陆的用户信息
		Userinfo user = (Userinfo) session.getAttribute("user");
		List<Fileinfo> list = fileinfoService.findByUserId(user.getUserId());
		model.addAttribute("list", list);
		return "list";
	}

	/**
	 * 文件上传: a.将文件上传到服务器端 D:/upload/${userName} b.将文件信息添加到数据库中fileinfo表
	 * 
	 * @throws IOException
	 * @throws IllegalStateException
	 */
	@RequestMapping("/upload")
	public String upload(MultipartFile[] file, HttpSession session) throws Exception {
		// 获取当前登陆的用户信息
		Userinfo user = (Userinfo) session.getAttribute("user");
		File uploadPath = new File("D:/upload/" + user.getUserName());
		// 上传文件的总大小<=剩余空间
		long totalSpace = 0, usedSpace = 0, freeSpace = 0;
		if (user.getUserType() == 1) {
			totalSpace = 32 * 1024 * 1024;// 普通用户拥有32M个人空间
		} else if (user.getUserType() == 2) {
			totalSpace = 128 * 1024 * 1024;// 普通用户拥有128M个人空间
		}
		File[] fs = uploadPath.listFiles();// 获取该用户上传目录下的所有文件
		for (File file2 : fs) {
			usedSpace += file2.length();// 计算已用空间大小
		}
		freeSpace = totalSpace - usedSpace;// 剩余空间=空间总大小-已用空间大小
		long uploadSize = 0;// 上传文件的总大小
		for (MultipartFile multipartFile : file) {
			long fileSize = multipartFile.getSize();// 获取上传文件的大小
			// 普通用户上传的单文件大小>=1M,抛出异常
			if (user.getUserType() == 1 && fileSize > 1 * 1024 * 1024) {
				throw new CustomException("普通用户上传单文件大小<=1M!");
			}
			// VIP用户上传的单文件大小>=2M,抛出异常
			if (user.getUserType() == 2 && fileSize > 2 * 1024 * 1024) {
				throw new CustomException("VIP用户上传单文件大小<=2M!");
			}
			uploadSize += fileSize;// 计算上传文件的总大小
		}
		if (uploadSize > freeSpace) {
			throw new CustomException("剩余空间不足!");
		}
		// 完成文件上传
		for (MultipartFile multipartFile : file) {
			String fileName = multipartFile.getOriginalFilename();
			long fileSize = multipartFile.getSize();
			String filePath = "D:/upload/" + user.getUserName() + "/" + fileName;// 文件保持路径
			String fileCode = MyMD5Util.createMD5(filePath);// 提取码
			// 上传文件
			multipartFile.transferTo(new File(filePath));
			// 将文件信息添加到数据库中
			Fileinfo f = new Fileinfo(fileName, fileSize, fileCode, filePath, user.getUserId());
			fileinfoService.add(f);
		}
		return "redirect:/fileinfo/list.action";
	}

	/**
	 * 根据提取码下载
	 * 
	 * @return
	 */
	@RequestMapping("/download")
	public ResponseEntity<byte[]> download(String fileCode) throws Exception {
		Fileinfo fileinfo = fileinfoService.findByFileCode(fileCode);
		String filePath = fileinfo.getFilePath();
		HttpHeaders headers = new HttpHeaders();
		String fileName = new String(fileinfo.getFileName().getBytes("UTF-8"), "iso-8859-1");
		headers.setContentDispositionFormData("attachment", fileName);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		ResponseEntity responseEntity = new ResponseEntity(FileUtils.readFileToByteArray(new File(filePath)), headers,
				HttpStatus.CREATED);
		return responseEntity;
	}

	/**
	 * 删除文件
	 * 
	 * @param fileId
	 * @return
	 */
	@RequestMapping("/delete")
	public String delete(int fileId) {
		int count = fileinfoService.delete(fileId);
		if (count > 0) {
			return "redirect:/fileinfo/list.action";
		}
		return "error";
	}
}
